<?php


namespace tmcore\services;


use Exception;
use Fastknife\Exception\ParamException;
use Fastknife\Service\BlockPuzzleCaptchaService;
use Fastknife\Service\ClickWordCaptchaService;
use think\captcha\facade\Captcha;
use tmcore\exceptions\ValidateException;

class CaptchaService
{
    protected $service;

    /**
     * CaptchaService constructor.
     * @param string $type 类型 blockPuzzle-滑动拼图 clickWord-文字点选
     * @param array $config
     */
    public function __construct($type = 'blockPuzzle', $config = [])
    {
        $sys_config = config('captcha');
        $config = array_merge($sys_config, $config);

        if($type == 'blockPuzzle') {
            $this->service = new BlockPuzzleCaptchaService($config);
        } else {
            $this->service = new ClickWordCaptchaService($config);
        }
    }

    /**
     * 获取验证信息
     * @return array
     */
    public function create(){
        return $this->service->get();
    }

    /**
     * 一次验证
     * @param $key
     * @param $code
     * @return boolean
     * @throws ValidateException
     */
    public function check($key, $code){
        try {
            $this->service->check($key, $code);
            return true;
        } catch ( Exception $e) {
            throw new ValidateException($e->getMessage());
        }
    }

    /**
     * 二次验证
     * @param $code
     * @return boolean
     * @throws ValidateException
     */
    public function verification($code){
        try {
            $this->service->verificationByEncryptCode($code);
            return true;
        } catch (ParamException $e) {
            throw new ValidateException($e->getMessage());
        }
    }

    /**
     * 验证码创建
     * @return array
     */
    public static function codeCreate(){
        $uniqid = uniqid(rand(00000,99999));
        $rs = Captcha::create();
        $base64_image = "data:image/png;base64," . base64_encode($rs->getData());
        $key = session('captcha.key');

        cache('admin_captcha_verify_' . $uniqid,$key, 24*60*60);
        return ['uniqid'=>$uniqid,'image'=>$base64_image];
    }

    /**
     * 验证码验证
     * @param $params
     * @return bool
     * @throws ValidateException
     */
    public static function codeVerify($params){
        $key = cache('admin_captcha_verify_' . $params['captchaUniqid']);
        if($key && password_verify(mb_strtolower($params['code'], 'UTF-8'), $key)){
            cache('admin_captcha_verify_'.$params['captchaUniqid'],null);
            return true;
        }else{
            throw new ValidateException('验证码检验失败');
        }
    }
}